import type { Recordable } from '@vben/types';

import { h } from 'vue';

import { IconifyIcon } from '@vben/icons';
import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { isFunction, isString } from '@vben/utils';

import { Button, Image, Popconfirm, Tag } from 'ant-design-vue';

import { useVbenForm } from './form';

setupVbenVxeTable({
  configVxeTable: (vxeUI) => {
    vxeUI.setConfig({
      table: {
        autoResize: true,
        showHeaderOverflow: true,
      },
      grid: {
        align: 'center',
        rowConfig: {
          isHover: true,
        },
        border: false,
        columnConfig: {
          resizable: true,
          minWidth: 100,
        },
        minHeight: 180,
        formConfig: {
          // 全局禁用vxe-table的表单配置，使用formOptions
          enabled: false,
        },
        proxyConfig: {
          autoLoad: true,
          response: {
            result: 'items',
            total: 'total',
            list: 'items',
          },
          showActiveMsg: true,
          showResponseMsg: false,
        },
        round: true,
        showOverflow: true,
        size: 'small',
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellImage' },
    vxeUI.renderer.add('CellImage', {
      renderTableDefault(_renderOpts, params) {
        const { column, row } = params;
        return h(Image, { src: row[column.field] });
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellLink' },
    vxeUI.renderer.add('CellLink', {
      renderTableDefault(renderOpts) {
        const { props } = renderOpts;
        return h(
          Button,
          { size: 'small', type: 'link' },
          { default: () => props?.text },
        );
      },
    });

    vxeUI.renderer.add('CellHeight', {
      renderTableDefault(renderOpts, params) {
        const { props } = renderOpts;
        const { row, column } = params;
        const { height } = props || {};
        return h('div', { class: `h-[${height}px]` }, row[column.field]);
      },
    });

    /**
     * 表单查看详情按钮
     * 表格配置项可以用 cellRender: { name: 'CellButtonInfo' },
     */
    vxeUI.renderer.add('CellButtonInfo', {
      renderTableDefault(_renderOpts, params) {
        const { props } = _renderOpts;
        const { column, row } = params;
        const value = row[column.field];
        return h(
          Button,
          {
            type: 'link',
            onClick: () => props?.onClick(row),
          },
          { default: () => value },
        );
      },
    });

    /**
     * 表单列上下渲染
     * 表格配置项可以用 cellRender: { name: 'CellTopDown' ,props},
     * props: {
     *   top: 'top',上面的属性名
     *   down: 'down',下面的属性名
     *   topDict: topDict,上面的字典数组
     *   downDict: downDict,下面的字典数组
     * }

     */
    vxeUI.renderer.add('CellTopDown', {
      renderTableDefault(_renderOpts, params) {
        const { props } = _renderOpts;
        const { row } = params;
        const { top, down, topDict, downDict } = props || {};
        let topValue: string = row[top];
        let downValue = row[down];
        if (topDict) {
          // 修改：将 topValue 定义为 let 变量，使其可以重新赋值
          topValue = topDict.find(
            (item: { value: any }) => item.value === row[top],
          )?.label;
        }
        if (downDict) {
          downValue = downDict.find(
            (item: { value: any }) => item.value === row[down],
          )?.label;
        }
        return h('div', { class: 'flex flex-col' }, [
          h('div', { class: 'text-xs' }, topValue),
          h('div', { class: 'text-xs' }, downValue),
        ]);
      },
    });

    /**
     * 是否字典状态标签
     * 表格配置项可以用 cellRender: { name: 'CellTag' },
     */
    vxeUI.renderer.add('CellTag', {
      renderDefault(_renderOpts, params) {
        const { column, row } = params;
        const value = row[column.field];
        const color =
          // eslint-disable-next-line unicorn/no-nested-ternary
          value === 'Y' ? 'blue' : value === 'N' ? 'red' : 'blue';
        let content = value;
        switch (value) {
          case 'N': {
            content = '否';
            break;
          }
          case 'Y': {
            content = '是';
            break;
          }
          default: {
            content = value;
            break;
          }
        }
        return h(
          Tag,
          {
            color,
            // closable: false,
          },
          content,
        );
      },
    });

    /**
     * 注册表格的操作按钮渲染器
     */
    vxeUI.renderer.add('CellOperation', {
      renderTableDefault({ attrs, options, props }, { column, row }) {
        const defaultProps = { size: 'small', type: 'link', ...props };
        let align = 'end';
        switch (column.align) {
          case 'center': {
            align = 'center';
            break;
          }
          case 'left': {
            align = 'start';
            break;
          }
          default: {
            align = 'end';
            break;
          }
        }
        const presets: Recordable<Recordable<any>> = {
          delete: {
            danger: true,
            text: '删除',
          },
          edit: {
            text: '修改',
          },
        };
        const operations: Array<Recordable<any>> = (
          options || ['edit', 'delete']
        )
          .map((opt) => {
            if (isString(opt)) {
              return presets[opt]
                ? { code: opt, ...presets[opt], ...defaultProps }
                : {
                    code: opt,
                    text: opt,
                    ...defaultProps,
                  };
            } else {
              return { ...defaultProps, ...presets[opt.code], ...opt };
            }
          })
          .map((opt) => {
            const optBtn: Recordable<any> = {};
            Object.keys(opt).forEach((key) => {
              optBtn[key] = isFunction(opt[key]) ? opt[key](row) : opt[key];
            });
            return optBtn;
          })
          .filter((opt) => opt.show !== false);

        function renderBtn(opt: Recordable<any>, listen = true) {
          return h(
            Button,
            {
              ...props,
              ...opt,
              icon: undefined,
              onClick: listen
                ? () =>
                    attrs?.onClick?.({
                      code: opt.code,
                      row,
                    })
                : undefined,
            },
            {
              default: () => {
                const content = [];
                if (opt.icon) {
                  content.push(
                    h(IconifyIcon, { class: 'size-5', icon: opt.icon }),
                  );
                }
                content.push(opt.text);
                return content;
              },
            },
          );
        }

        function renderConfirm(opt: Recordable<any>) {
          return h(
            Popconfirm,
            {
              getPopupContainer(el) {
                return el.closest('tbody') || document.body;
              },
              placement: 'topLeft',
              title: `删除${attrs?.nameTitle || ''}`,
              ...props,
              ...opt,
              icon: undefined,
              onConfirm: () => {
                attrs?.onClick?.({
                  code: opt.code,
                  row,
                });
              },
            },
            {
              default: () => renderBtn({ ...opt }, false),
              description: () =>
                h(
                  'div',
                  { class: 'truncate' },
                  `确定要删除${row[attrs?.nameField || 'name']}吗？`,
                ),
            },
          );
        }

        const btns = operations.map((opt) =>
          opt.code === 'delete' ? renderConfirm(opt) : renderBtn(opt),
        );
        return h(
          'div',
          {
            class: 'flex table-operations',
            style: { justifyContent: align },
          },
          btns,
        );
      },
    });

    // 这里可以自行扩展 vxe-table 的全局配置，比如自定义格式化
    // vxeUI.formats.add
  },
  useVbenForm,
});

export { useVbenVxeGrid };
export type OnActionClickParams<T = Recordable<any>> = {
  code: string;
  row: T;
};
export type OnActionClickFn<T = Recordable<any>> = (
  params: OnActionClickParams<T>,
) => void;

export type * from '@vben/plugins/vxe-table';
